package com.hyjiacan.apps.audionly.data

import android.util.Log
import com.hyjiacan.apps.audionly.data.model.AudioParam
import com.hyjiacan.apps.audionly.data.model.TaskInfo
import com.hyjiacan.apps.audionly.data.model.VideoFile
import com.hyjiacan.apps.audionly.data.repository.TaskRepository
import com.hyjiacan.apps.audionly.utils.ExoAudioExtractor
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Date
import java.util.UUID

/**
 * 任务管理器，负责管理音频提取任务的生命周期
 */
import android.content.Context

class TaskManager(
    private val context: Context,
    private val taskRepository: TaskRepository,
    private val audioExtractor: ExoAudioExtractor
) {    private val TAG = "TaskManager"
    private val activeTasks = mutableMapOf<String, Job>()

    /**
     * 创建新任务
     * @param videoFile 视频文件
     * @param audioParam 音频参数
     * @return 创建的任务信息
     */
    suspend fun createTask(videoFile: VideoFile, audioParam: AudioParam): TaskInfo {
        val taskId = UUID.randomUUID().toString()
        val taskInfo = TaskInfo(
            id = taskId,
            videoFile = videoFile,
            audioParam = audioParam,
            status = TaskInfo.Status.PENDING,
            createTime = Date()
        )

        taskRepository.insertTask(taskInfo)
        Log.d(TAG, "Created new task: $taskId")
        return taskInfo
    }

    /**
     * 开始任务
     * @param taskId 任务ID
     * @param onProgressUpdate 进度更新回调
     * @return 是否成功开始
     */
    suspend fun startTask(
        taskId: String,
        onProgressUpdate: (taskId: String, progress: Int) -> Unit
    ): Boolean {
        val taskInfo = taskRepository.getTaskById(taskId)
        if (taskInfo == null) {
            Log.e(TAG, "Task not found: $taskId")
            return false
        }

        if (taskInfo.status != TaskInfo.Status.PENDING) {
            Log.e(TAG, "Task is not in PENDING state: $taskId, status: ${taskInfo.status}")
            return false
        }

        // 更新任务状态为处理中
        val updatedTask = taskInfo.copy(
            status = TaskInfo.Status.PROCESSING,
            startTime = Date()
        )
        taskRepository.updateTask(updatedTask)

        // 启动音频提取
        val job = CoroutineScope(Dispatchers.IO).launch {
            // 调用音频提取器
            audioExtractor.extractAudio(
                inputPath = updatedTask.videoFile.path,
                outputDir = "${context.cacheDir}/audio_output",
                outputFormat = when (updatedTask.audioParam.format.lowercase()) {
                    "aac" -> ExoAudioExtractor.OutputFormat.AAC
                    "mp3" -> ExoAudioExtractor.OutputFormat.MP3
                    "wav" -> ExoAudioExtractor.OutputFormat.WAV
                    "flac" -> ExoAudioExtractor.OutputFormat.FLAC
                    "ogg" -> ExoAudioExtractor.OutputFormat.OGG
                    "m4a" -> ExoAudioExtractor.OutputFormat.M4A
                    else -> ExoAudioExtractor.OutputFormat.MP3
                },
                scope = this,
                progressListener = { progress ->
                    onProgressUpdate(taskId, progress)
                },
                completionListener = { success, message ->
                    scope.launch(Dispatchers.IO) {
                        val finalStatus = if (success) TaskInfo.Status.COMPLETED else TaskInfo.Status.FAILED
                        val finishedTask = updatedTask.copy(
                            status = finalStatus,
                            endTime = Date()
                        )
                        taskRepository.updateTask(finishedTask)
                        activeTasks.remove(taskId)
                        Log.d(TAG, "Task completed: $taskId, status: $finalStatus, message: $message")
                    }
                }
            )
        }
        activeTasks[taskId] = job

        Log.d(TAG, "Started task: $taskId")
        return true
    }

    /**
     * 取消任务
     * @param taskId 任务ID
     * @return 是否成功取消
     */
    suspend fun cancelTask(taskId: String): Boolean {
        val taskInfo = taskRepository.getTaskById(taskId)
        if (taskInfo == null) {
            Log.e(TAG, "Task not found: $taskId")
            return false
        }

        if (taskInfo.status != TaskInfo.Status.PROCESSING) {
            Log.e(TAG, "Task is not in PROCESSING state: $taskId, status: ${taskInfo.status}")
            return false
        }

        // 取消协程
        activeTasks[taskId]?.cancel()
        activeTasks.remove(taskId)

        // 更新任务状态
        val cancelledTask = taskInfo.copy(
            status = TaskInfo.Status.FAILED,
            endTime = Date()
        )
        taskRepository.updateTask(cancelledTask)

        Log.d(TAG, "Cancelled task: $taskId")
        return true
    }

    /**
     * 获取所有任务
     * @return 任务列表
     */
    suspend fun getAllTasks(): List<TaskInfo> {
        return taskRepository.getAllTasks()
    }

    /**
     * 根据状态获取任务
     * @param status 任务状态
     * @return 任务列表
     */
    suspend fun getTasksByStatus(status: TaskInfo.Status): List<TaskInfo> {
        return taskRepository.getTasksByStatus(status)
    }

    /**
     * 检查任务是否活跃
     * @param taskId 任务ID
     * @return 是否活跃
     */
    fun isTaskActive(taskId: String): Boolean {
        return activeTasks.containsKey(taskId)
    }
}